package service;

import bean.Article;
import dao.util.ArticleCreate;
import mapper.ArticleMapper;

import java.util.List;

public class ArticleService {
    private final ArticleCreate create = new ArticleCreate();

    public List<Article> listAll() {
        try {
            ArticleMapper mapper = create.getMapperClass();
            List<Article> list = mapper.selectAll();
            return list;
        } catch (Exception e) {
            java.util.List<Article> demo = new java.util.ArrayList<>();
            for (int i = 1; i <= 10; i++) {
                Article a = new Article();
                a.setId(i);
                a.setTitle("示例文章 " + i);
                a.setContent("<p>这是用于预览的示例内容，数据库初始化后将替换。</p>");
                a.setTags("示例,预览");
                demo.add(a);
            }
            create.closeSession();
            return demo;
        }
    }

    public Article getById(Integer id) {
        ArticleMapper mapper = create.getMapperClass();
        Article a = mapper.selectById(id);
        create.closeSession();
        return a;
    }

    public int add(Article article) {
        ArticleMapper mapper = create.getMapperClass();
        int r = mapper.insertArticle(article);
        create.commit();
        create.closeSession();
        return r;
    }

    public int update(Article article) {
        ArticleMapper mapper = create.getMapperClass();
        int r = mapper.updateArticle(article);
        create.commit();
        create.closeSession();
        return r;
    }

    public int delete(Integer id) {
        ArticleMapper mapper = create.getMapperClass();
        int r = mapper.deleteLogical(id);
        create.commit();
        create.closeSession();
        return r;
    }

    public List<Article> recommend(int limit) {
        try {
            ArticleMapper mapper = create.getMapperClass();
            List<Article> list = mapper.selectRecommend(limit);
            create.closeSession();
            return list;
        } catch (Exception e) {
            // 兜底推荐两篇示例文章
            java.util.List<Article> demo = new java.util.ArrayList<>();
            for (int i = 1; i <= Math.max(2, limit); i++) {
                Article a = new Article();
                a.setId(100 + i);
                a.setTitle("推荐示例 " + i);
                a.setContent("<p>用于预览的推荐内容。</p>");
                a.setTags("推荐,示例");
                demo.add(a);
            }
            return demo.subList(0, Math.min(limit, demo.size()));
        }
    }
}